package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

import bot.City;
import bot.FullCycleBot;
import bot.Util;

public class AutoButton extends JButton{
	/**
	 * Default Serialization
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Text field that contains the url of the page being edited.
	 */
	private static JTextField url;
	/**
	 * Text field that contains the date of access for the page.
	 */
	private static JTextField date;
	/**
	 * Text area that contains the source code for the wikipedia page.
	 */
	private static JTextArea code;
	
	public static JButton next;
	private static JFrame frame;
	
	private static City city;
	private static String nextCity;
	
	public AutoButton(JTextField textCity, JTextField textDate, JTextArea pageSource){
		super("Auto");
		url = textCity;
		date = textDate;
		code = pageSource;
		
		addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg) {
				try{
					frame = new JFrame();
					JPanel panel = new JPanel();
					next = new JButton("next");
					panel.add(next);
					frame.add(panel);
					frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					frame.setVisible(true);
					frame.setSize(200, 200);
					
					next.addActionListener(new ActionListener(){
						@Override
						public void actionPerformed(ActionEvent arg0) {
							action();
						}
					});
				}
				catch (IllegalArgumentException e){
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "Invaild city name");
				} 
			}
		});
		
	}
	
	public static void action(){
		nextCity = Util.getLastEntry(BotGui.linksToDo, BotGui.linksDone);
		if (nextCity == null){
			frame.dispose();
			return;
		}
		try{
			city = new City(nextCity, BotGui.data);
			code.setText("");
			url.setText(nextCity);
			editCity();
		}
		catch (IllegalArgumentException e){
			Util.addTextToFile(nextCity, BotGui.citiesNotFound);
			AutoButton.action();
		}
	}
	
	private static void editCity(){
		FullCycleBot bot = new FullCycleBot(nextCity, city, date.getText(), code, false);
		bot.edit();
	}
}
